/*
 * issue:
 * 	商品详情 增加更新以后 不能够disabled了。
 * 	当类别只有一个的时候，那个下拉了就不能再滑上去了。
 */

var ProductController = function($scope, $location, $http, $upload, $log) {

	// angularjs本身是异步的，不是同步，所以在执行的时候要小心异步的问题。

	$scope.baseUrl = zimgeUrl;
	$scope.formatImage = "?w=200&h=200";
	$scope.open = "open";
	$scope.images = [];

	var data = new Array();
	var category = new Array();
	var map = {};

	$scope.getProductByid = function(categoryId) {
		$http.get('../product/listbycid2?categoryId=' + categoryId).success(function(response) {
			$scope.products[map[categoryId]] = response;
		});
	}

	$scope.getAllProductCategory = function() {
		$http.get('../category/list').success(function(response) {
			$scope.productCategorys = response;
			// 这个是有问题的，问题出在如果后面的array太大会有异常
			data.push.apply(data, response);
			$scope.products = new Array([ data.length ]);
			for (var i = 0; i < data.length; i++) {
				// 这个地方i的变化是递增的，也就是有序的，而data[i].id因为异步的原因可能顺序会乱
				map[data[i].id] = i;
				$scope.getProductByid(data[i].id);
			}

		});
	}

	/*
	 * 由于把修改和增加合并了所以这个没用用了 修改信息
	 * save(product.category.id,product.description,product.price,product.note,product.thumBId,imageIds)
	 * 
	 * $scope.save=function(productId,categoryId,description,price,note,thumbId,imageIds){
	 * 
	 * $scope.savedata={'id':productId,'description':description,'price':price,'note':note,'thumbId':thumbId,'imageIds':imageIds,
	 * 'categoryId':categoryId}; $http({ method:"post", url :
	 * '../product/modify', data : $.param($scope.savedata), // pass in data
	 * as strings headers : { 'Content-Type':
	 * 'application/x-www-form-urlencoded'}
	 * 
	 * }).success(function(data) { window.alert("修改成功");
	 * $scope.getProductByid(categoryId);
	 * 
	 * }).error(function(){ window.alert("修改失败，请重新添加"); }); }
	 */

	/*
	 * add product: isuse: users don't choose for productcategory
	 */
	$scope.submitdata = function(product, pristine) {

		if (angular.isUndefined(product.thumbId)) {
			sweetAlert("请添加产品图片");
			return;
		}

		var urlpath = "";
		$scope.adddata = {
			'description' : product.description,
			'price' : product.price,
			'note' : product.note,
			'thumbId' : product.thumbId,
			'imageIds' : product.imageIds,
			'specification' : product.specification,
			'categoryId' : product.category.id,
			'amount' : product.amount
		};
		console.log(product.id);
		if (product.id) {
			urlpath = "../product/modify";
			$scope.adddata['id'] = product.id;
			$scope.adddata['status'] = product.status;
		} else {
			urlpath = "../product/add";
		}
		$http({
			method : "post",
			url : urlpath,
			data : $.param($scope.adddata), // pass in data as
			// strings
			headers : {
				'Content-Type' : 'application/x-www-form-urlencoded'
			}

		}).success(function(data) {
			// console.log(data);
			if (data['code'] == 0) {
				swal({
					title : "警告",
					text : "您无权限进行操作",
					timer : 2000
				});
				// 重定向到product那里了
				$location.path("error");
				return;
			} else {
				if (!product.id) {
					product.id = data['object'];
				}

				sweetAlert("数据已更新");
				$scope.getProductByid(product.category.id);

			}

		}).error(function() {
			sweetAlert("数据更新失败，请重新更新");
		});
	}

	/*
	 * 按照产品的id去拿到产品信息
	 */
	$scope.getProduct = function(id) {

		$http.get('../product/get?id=' + id).success(function(response) {

			$scope.nproduct = response;
			if ($scope.nproduct.imageIds)
				$scope.images = $scope.nproduct.imageIds.split(";");

		});

	}

	/**
	 * bootStrap Switch
	 */
	$scope.filterProduct = function(product) {

		if (angular.isDefined(product.id))
			return product;

		// $('input[name="my-checkbox"]').on('switchChange.bootstrapSwitch',
		// function(event, state) {
		//			
		// console.log(this); // true | false
		// });
	}
	$scope.changeStatus = function(product) {
		console.log(product);
		$scope.submitdata(product);
	}

	/*
	 * 请空nproduct对象
	 */
	$scope.add = function(productcategoryId, productcategoryDescription) {

		// js里面一般要不是array要不就是map
		$scope.nproduct = {};
		$scope.images = [];
		$scope.nproduct.category = {};
		$scope.nproduct.category.id = productcategoryId;
		$scope.nproduct.category.description = productcategoryDescription;
	}

	/**
	 * 上传文件
	 */
	$scope.onFileSelect = function($files) {
		// $files: an array of files selected, each file has name, size,
		// and type.
		for (var i = 0; i < $files.length; i++) {
			var file = $files[i];

			$scope.upload = $upload.http({
				url : uploadUrl,
				headers : {
					'Content-Type' : file.type.split("/")[1]
				},
				data : file,
			}).progress(function(evt) {
				// console.log('percent: ' + parseInt(100.0 *
				// evt.loaded / evt.total));
			}).success(function(data) {

				$scope.nproduct.thumbId = data['info']['md5'];
				$log.info(data);
			}).error(function(data) {
				// error
				sweetAlert("上传图片失败");
			});

		}
	}

	/*
	 * 上传imageIds
	 */
	$scope.onFileSelectadd = function($files) {
		for (var i = 0; i < $files.length; i++) {
			var file = $files[i];

			$scope.upload = $upload.http({
				url : uploadUrl,
				headers : {
					'Content-Type' : file.type.split("/")[1]
				},
				data : file,
			}).progress(function(ev) {
				// progress
			}).success(function(data) {
				// 这里不能写$scope.naproduct.category.id是因为点击图片会还原数据
				if ($scope.nproduct.imageIds != "" && $scope.nproduct.imageIds)
					$scope.nproduct.imageIds = $scope.nproduct.imageIds + ";" + data['info']['md5'];
				else
					$scope.nproduct.imageIds = data['info']['md5'];

				$scope.images.push(data['info']['md5']);
				// console.log($scope.nproduct.imageIds);
			}).error(function(data) {
				// error
				sweetAlert("上传图片失败");
			});
		}
	}

	/*
	 * 删除操作
	 */
	$scope.deleteproduct = function(id, categoryid) {

		/*
		 * $http({ method:"post", url : "../product/delete", params :
		 * {'id':id}, headers : { 'Content-Type':
		 * 'application/x-www-form-urlencoded'}
		 * 
		 * }).success(function(data) {
		 * 
		 * sweetAlert("删除成功"); $scope.getProductByid(categoryid);
		 * }).error(function(){ window.alert("删除失败，请重新添加"); });
		 */
	}

	/*
	 * 删除缩略图 有可能会有坑
	 */
	$scope.deleteimage = function(index) {
		// $scope.images.slice(index,1);
		// console.log($scope.nproduct.imageIds);
		$scope.images.splice(index, 1);
		// console.log($scope.images.length);
		// 传换成字符串
		for (var i = 0; i <= $scope.images.length; i++) {
			if ($scope.images[i] != '' && $scope.images[i])
				$scope.nproduct.imageIds = $scope.nproduct.imageIds + ";" + $scope.images[i];
			else
				$scope.nproduct.imageIds = null;
		}
	}

	/**
	 * for single picture
	 */
	$scope.pass = function(thumbId) {

		$scope.$parent.singlepicture = $scope.baseUrl + thumbId + "?p=0";
	}

	/**
	 * 产品详情
	 * 
	 */
	$scope.addProductDetail = function() {

		if ($scope.productDetailItems == null) {
			$scope.productDetailItems = [];
		}

		$scope.productDetailItems.push(new Object({
			'flag' : 1,
			'image' : "",
			'detail' : ""
		}));

	}

	$scope.showProductDetail = function(id,thumbId) {
		// $log.info(product.id);
		$scope.productID = id;
		$http.get('../productDetail/get?productId=' + id).success(function(response) {
			$log.info("进入侧边栏", response);
			// list
			$scope.productDetail = response;
			// items
			if ($scope.productDetail.details == "null") {
				$scope.productDetailItems = [];
			} else {
				$scope.productDetailItems = eval('(' + $scope.productDetail.details + ')');
			}
			// 判断是否有大的标题图片
			if ($scope.productDetail.imageId != null) {
				// $scope.showProductImageId =
				// $scope.productDetail.imageId.split("_")[0];
			} else {
				$scope.productDetail = {
					"imageId" : ""
				};
				$log.info($scope.productDetail);
				// $scope.showProductImageId = "";
			}
			$scope.showProductImageId=thumbId;

		}).error();
	}

	$scope.showPicture = function(topbanner) {
		if (topbanner == null) {
			topbanner.showimageId = "";
			return topbanner;
		}

		if (angular.isUndefined(topbanner.image)) {
			topbanner.image = "";
			return;
		}
		topbanner.showimageId = topbanner.image.split('_')[0];

		return topbanner;
	}

	// 移除item
	$scope.deletetopbanner = function(newsDetail, item) {
		newsDetail.splice(newsDetail.indexOf(item), 1);
	}

	

	$scope.uploadProductDetail = function($files, topbanner) {
		for (var i = 0; i < $files.length; i++) {
			var file = $files[i];
			$scope.upload = $upload.http({
				// url : 'http://pay.dxyxx.com/upload',
				url : uploadUrl,
				headers : {
					'Content-Type' : file.type.split("/")[1]
				},
				data : file,
			}).success(function(data) {
				topbanner.image = topbanner.showimageId = data['info']['md5'];

				$http.get(getImageInfo + '?md5=' + topbanner.image).success(function(response) {
					topbanner.image = topbanner.image + "_" + response['info']["width"] + "_" + response['info']["height"];
				}).error();
			}).error(function(data) {

				sweetAlert("上传图片失败");
			});
		}
	}

	// 保存到数据库
	$scope.savaData = function(newsDetail) {

		var object = [];
		for ( var item in newsDetail) {
			if (newsDetail[item].detail == null || newsDetail[item].detail == "") {
				sweetAlert("请添加描述");
				return;
			}
			object.push({
				"image" : newsDetail[item].image,
				"detail" : newsDetail[item].detail
			});
		}

		$scope.productDetail.details = JSON.stringify(object);
		url = "../productDetail/update";

		$http({
			method : "POST",
			url : url,
			data : $.param({
				"productDetails" : $scope.productDetail.details,
				"productId" : $scope.productID
			}),
			headers : {
				'Content-Type' : 'application/x-www-form-urlencoded'
			}
		}).success(function(data) {
			if (data == 0) {
				sweetAlert(data.info);
			} else {
				sweetAlert("操作成功");
			}
		}).error(function() {
			sweetAlert("更新失败");
		});
	}

	$scope.getAllProductCategory();

}
